part of "../taobao.dart";

/// 获取淘宝订单
/// API地址：https://open.taobao.com/api.htm?spm=a219a.7386797.0.0.1fb4669aCMTcpQ&source=search&docId=45011&docType=2
Future<List<TaobaoTrade>> getOrder() async {
  // 先发送一个简单的请求，查看总共有多少条信息
  final uri = getTaobaoUri("taobao.open.trades.sold.get", {
    "fields": "tid",
    "page_size": "1",
    // 重置商家编码的时间，避免比如"心与物"没有商家编码的囧境
    "start_created": "2024-07-19 00:00:00",
  });
  final Json rawBody = await sendTaobaoRequest(uri);
  int totalResults = rawBody["open_trades_sold_get_response"]["total_results"];

  // 将信息除以100后取天花板，就是需要获取的所有订单数量
  int totalPages = (totalResults / 100).ceil();

  // 循环n次，分别获取第n页的订单信息，将它们合并起来后返回
  List<TaobaoTrade> trades = [];
  await loop(totalPages, (page) async {
    print("现在执行第$page次请求");
    final uri = getTaobaoUri("taobao.open.trades.sold.get", {
      "fields": "tid,status,payment,orders,buyer_nick,created,pay_time",
      "page_size": "100",
      "page_no": page.toString(),
      "start_created": "2024-07-19 00:00:00",
    });
    final rawBody = await sendTaobaoRequest(uri);

    JsonList ordersThisPage =
        rawBody["open_trades_sold_get_response"]["trades"]["trade"];

    for (final order in ordersThisPage) {
      trades.add(TaobaoTrade.fromRaw(order));
    }
    print("第$page次请求执行完毕");
  });

  // 当所有信息都获取完毕时，返回汇总的orders
  return trades;
}
